package com.edgelight.controller;

import com.edgelight.dao.NewsRepository;
import com.edgelight.pojo.News;
import com.edgelight.pojo.resp.BaseResp;
import com.edgelight.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;

import javax.annotation.Resource;
import java.util.Map;


@RestController
@RequestMapping("news")
public class NewsController {

    @Resource
    private NewsService newsService;

    @Autowired
    NewsRepository newsRepository;

    @ApiOperation(value="查询全部")
    @RequestMapping("/findAll/{page}/{size}")
    public BaseResp findAll(@PathVariable("page")Integer page, @PathVariable("size")Integer size){
        return newsService.findAll(page,size);
    }



    @ApiOperation(value="查询一条新闻")
    @RequestMapping("/findAll/{id}")
    public BaseResp findAll(@PathVariable("id")Integer id){
        BaseResp baseResp = new BaseResp() ;
        News news =newsRepository.getOne(id);
        if (news!= null){
            return baseResp.SUCCESS();
        }return baseResp.ERROR();

    }




    @PostMapping("/deleteById")
    @ApiOperation(value="通过id删除")
    //这里为什么是map
    //前端传递的是map? json=map?

    public BaseResp deleteById(@RequestBody Map map){
        return newsService.delete(Integer.valueOf(map.get("id").toString()));
    }

    /**
     * 新增数据
     *
     * @param news 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<News> add(News news) {
        return ResponseEntity.ok(this.newsService.insert(news));
    }

    /**
     * 编辑数据
     *
     * @param news 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<News> edit(News news) {
        return ResponseEntity.ok(this.newsService.update(news));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Integer id) {
        return ResponseEntity.ok(this.newsService.deleteById(id));
    }

}

